
package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.order.configure.OrderDelayedMqConfig;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.SkuLockVo;
import com.spzx.product.domain.SkuPrice;
import com.spzx.product.domain.SkuStockVo;


import com.spzx.rabbit.constant.MqConst;
import com.spzx.rabbit.service.RabbitService;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import io.jsonwebtoken.lang.Assert;
import jakarta.annotation.Resource;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-11-01
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    RemoteCartService remoteCartService;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    RemoteUserAddressService remoteUserAddressService;

    @Resource
    RemoteProductService remoteProductService;

    @Resource
    OrderLogMapper orderLogMapper;

   @Resource
    RabbitService rabbitService;


    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    @Override
    public TradeVo trade() {
        Long userId = SecurityContextHolder.getUserId();

        // 封装一个TradeVo对象
        List<OrderItem> orderItemList = new ArrayList<>();

        // 远程调用购物车列表
        R<List<CartInfo>> cartListR = remoteCartService.cartList("inner");
        int code = cartListR.getCode();
        Assert.isTrue(code==200, "远程调用失败");
        List<CartInfo> cartInfoList = cartListR.getData();

        orderItemList = cartInfoList.stream().map(cart->{
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuPrice(cart.getSkuPrice());
            // orderItem.setOrderId();// 暂时没有，结算页是一个展示订单详情的页面，没有订单id
            orderItem.setThumbImg(cart.getThumbImg());
            orderItem.setSkuId(cart.getSkuId());
            orderItem.setSkuName(cart.getSkuName());
            orderItem.setSkuNum(cart.getSkuNum());
            return orderItem;
        }).collect(Collectors.toList());

        // 总金额
        BigDecimal sum = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            sum = sum.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(sum);
        // 将结算码存入redis
        String tradeNo = generateTradeNo(userId);
        tradeVo.setTradeNo(tradeNo);// 结算码
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Transactional
    @Override
    public Long submitOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        String tradeNo = orderForm.getTradeNo();// 交易码
        Long userAddressId = orderForm.getUserAddressId();// 收获地址id

        // 校验交易码
        Boolean b = checkTradeNo(tradeNo);
        Assert.isTrue(b, "交易码校验失败");

        // 查询收获地址
        R<UserAddress> addressR = remoteUserAddressService.getUserAddress(userAddressId, "inner");
        UserAddress userAddress = addressR.getData();

        // 实时价格信息
        List<Long> skuIds = orderItemList.stream().map(orderItem -> {
            return orderItem.getSkuId();
        }).collect(Collectors.toList());
        List<SkuPrice> skuPrices = remoteProductService.getSkuPriceList(skuIds, "inner").getData();
        Map<Long,BigDecimal> map = skuPrices.stream().collect(Collectors.toMap(SkuPrice::getSkuId,SkuPrice::getSalePrice));
        // 校验价格
        for (OrderItem orderItem : orderItemList) {
            if(orderItem.getSkuPrice().compareTo(map.get(orderItem.getSkuId()))!=0){
                // 更新购物车价格
                R<Boolean> updateCartPriceR = remoteCartService.updateCartPrice("inner");
                throw new RuntimeException("价格变动");
            }
        }

        // 锁定库存
        List<SkuLockVo> skuLockVoList = new ArrayList<>();
        for (OrderItem orderItem : orderItemList) {
            Long skuId = orderItem.getSkuId();
            Integer skuNum = orderItem.getSkuNum();
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuNum(skuNum);
            skuLockVo.setSkuId(skuId);
            skuLockVoList.add(skuLockVo);
        }
        Boolean stockBoolean = remoteProductService.checkAndLock(tradeNo,skuLockVoList, "inner").getData();
        // 断言
        Assert.isTrue(stockBoolean, "库存锁定失败");

        // 保存订单信息
        Long orderId = saveOrder(orderForm);
        // 保存订单日志
        OrderLog orderLog = new OrderLog();
        //记录日志
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        // 删除购物车信息，通过mq异步服务
        System.out.println("通过mq发送清理购物车的消息");
        R<Boolean> removeCheckedCartR = remoteCartService.removeCheckedCart("inner");

        // 延迟关单，通过mq异步服务configure
        System.out.println("通过mq发送延迟关单的消息");
        rabbitService.sendDealyMessage(OrderDelayedMqConfig.exchange_delay_order,OrderDelayedMqConfig.routing_delay_order, tradeNo, 20);
        return orderId;
    }

    @Override
    public void cancelOrder(String tradeNo) {
        System.out.println("执行sql语句，关闭订单");
        OrderInfo orderInfo = baseMapper.selectOne(new QueryWrapper<OrderInfo>().eq("order_no", tradeNo));
        orderInfo.setOrderStatus(-1);
        int i = baseMapper.updateById(orderInfo);
        // 释放库存
        rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK, tradeNo);

    }

    private Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        baseMapper.insert(orderInfo);// 生成orderId

        // 保存详情
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        return orderInfo.getId();
    }

    private Boolean checkTradeNo(String tradeNo) {
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        String tradeNoCache = (String)redisTemplate.opsForValue().get(userTradeKey);
        if(tradeNo.equals(tradeNoCache)){
            redisTemplate.delete(userTradeKey);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

}
